﻿using CommonServiceLocator;
using GalaSoft.MvvmLight.Ioc;
using GalaSoft.MvvmLight;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GJB.ML.Message.ViewModel
{
    public class ViewModelLocator
    {
        /// <summary>
        /// Initializes a new instance of the ViewModelLocator class.
        /// </summary>
        public ViewModelLocator()
        {
            //ServiceLocator --> SimpleIoc 用来对象的创建   IOC思想的体现
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

            ////if (ViewModelBase.IsInDesignModeStatic)
            ////{
            ////    // Create design time view services and models
            ////    SimpleIoc.Default.Register<IDataService, DesignDataService>();
            ////}
            ////else
            ////{
            ////    // Create run time view services and models
            ////    SimpleIoc.Default.Register<IDataService, DataService>();
            ////}

            //IOC容器里注册了一个对象：MainViewModel  没有示例 类型  反射
            SimpleIoc.Default.Register<MainViewModel>();

            //SimpleIoc.Default.Register<IService, Service.Service>();
        }

        /// <summary>
        /// 从IOC容器里获取对象 MainViewModel  调用这个属性 就会创建一个实例
        /// </summary>
        public MainViewModel Main
        {
            get
            {
                return ServiceLocator.Current.GetInstance<MainViewModel>();
            }
        }

        //1.怎么用
        //2.为什么要这么用？

        public void Cleanup<T>() where T : ViewModelBase
        {
            ServiceLocator.Current.GetInstance<T>().Cleanup();
            //对象的收尾
            SimpleIoc.Default.Unregister<T>();
            SimpleIoc.Default.Register<T>();//为了下次打开使用
        }
    }
}
